package org.apache.ibatis.test;

import org.apache.ibatis.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author hanson.huang
 * @version V1.0
 * @ClassName test
 * @date 2025/1/6 13:32
 **/
public class test {

  @Test
  void test() throws IOException {
    String resource = "org/apache/ibatis/test/mybatis.xml";
    //1.读取resources下面的mybatis.xml文件
    InputStream inputStream = Resources.getResourceAsStream(resource);
    //2.使用SqlSessionFactoryBuilder创建SqlSessionFactory
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //3.通过sqlSessionFactory创建SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //4.获取mapper对象
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    /**
     * 由于所有的 Mapper 都是 MapperProxy 代理对象，所以任意的方法都是执行MapperProxy 的invoke()方法
     * {@link org.apache.ibatis.binding.MapperProxy#invoke}
     */
    //5.执行SQL
    User user = userMapper.selectUser(1);
    System.out.println(user);
    sqlSession.close();
  }
}
